package br.com.vagacerta.bd;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import br.com.vagacerta.modelo.Mensalista;

public class Canceladao {

	private Connection connection;

	public Canceladao() {

		this.connection = new ConnectionFactory().getConnection();
	}

	
	public Mensalista verificaCupom(Mensalista men) {
		try {

			Mensalista m = new Mensalista();

			String sql = "select c.NOME_CUPOM  from cupom c inner join pagamento pag on "
					+ "c.COD_CUPOM = pag.COD_CUPOM where c.NOME_CUPOM = ? and c.STATUS_CUPOM = 1 and pag.STATUS_PAGAMENTO = 1";

			PreparedStatement stmt = connection.prepareStatement(sql);
			stmt.setString(1, men.getCod_cupom());

			ResultSet rs = stmt.executeQuery();

			while (rs.next()) {

				m.setCod_cupom(rs.getString(("NOME_CUPOM")));

			}

			rs.close();
			stmt.close();

			return m;

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}

	public void mudaStatusCupomAposSaida(String nomeCupom) {
		try {

			String sql = "UPDATE CUPOM SET STATUS_CUPOM = 0, COD_CANCELA = NULL WHERE NOME_CUPOM = ?";

			PreparedStatement stmt;
			stmt = connection.prepareStatement(sql);

			stmt.setLong(1, Long.parseLong(nomeCupom));

			stmt.execute();
			stmt.close();

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}
	
	
	public void mudaStatusVagaAposSaida(String nomeCupom) {
		try {

			String sql = "UPDATE VAGA AS V INNER JOIN CUPOM AS C ON C.COD_VAGA = V.COD_VAGA SET STATUS_VAGA = 0 WHERE C.NOME_CUPOM = ?";

			PreparedStatement stmt;
			stmt = connection.prepareStatement(sql);

			stmt.setLong(1, Long.parseLong(nomeCupom));

			stmt.execute();
			stmt.close();

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}

}
